package logs

import (
	"errors"
	"time"

	"gitee.com/xgotool/sqlite-logs-more/model"
	"gitee.com/xgotool/sqlite-logs-more/service/rootdb"
)

// 获取日志详情信息
//
//	id	获取范围段的id类型
//	did	设备ID
//	inf	波动时间范围，纳秒，// 默认范围波动为60秒
func AllLogInfo(id, did int64, inf time.Duration) ([]LogSearch, error) {
	if id <= 0 {
		return nil, errors.New("日志ID未传输")
	}
	if did <= 0 {
		return nil, errors.New("设备ID未传输")
	}
	if inf <= 0 {
		inf = time.Second * 60
	}
	id_min, id_max := id-inf.Nanoseconds(), id+inf.Nanoseconds()
	// 获取当前存在的设备列表
	files, err := rootdb.FileListAll(id, id)
	if err != nil {
		return nil, err
	}
	rets := []LogSearch{}
	// 进行pipe日志搜索
	for i := 0; i < len(files); i++ {
		db, err := connect_file(files[i].Path)
		if err != nil {
			rets = append(rets, LogSearch{
				Type:     "open_error",
				FileName: files[i].Name,
				Error:    err.Error(),
			})
			continue
		}
		// pipe日志
		pipe_info := LogSearch{
			Type:     "pipe",
			FileName: files[i].Name,
		}
		pip, pips := model.PipeLog{}, []model.PipeLog{}
		err = db.Table(pip.TableName()).
			Where("id >= ?", id_min).
			Where("did", did).
			Where("id < ?", id_max).
			Order("id DESC").
			Find(&pips).
			Error
		if err != nil {
			pipe_info.Error = err.Error()
		}
		pipe_info.PipeLog = pips
		rets = append(rets, pipe_info)

		// app日志
		app_info := LogSearch{
			Type:     "app",
			FileName: files[i].Name,
		}
		app, apps := model.AppLog{}, []model.AppLog{}
		err = db.Table(app.TableName()).
			Where("id >= ?", id_min).
			Where("did", did).
			Where("id < ?", id_max).
			Order("id DESC").
			Find(&apps).
			Error
		if err != nil {
			app_info.Error = err.Error()
		}
		app_info.AppLog = apps
		rets = append(rets, app_info)

		// quest日志搜素
		quest_info := LogSearch{
			Type:     "quest",
			FileName: files[i].Name,
		}
		quest, quests := model.QuestLog{}, []model.QuestLog{}
		err = db.Table(quest.TableName()).
			Where("id >= ?", id_min).
			Where("id < ?", id_max).
			Where("did", did).
			Order("id DESC").
			Find(&quests).
			Error
		if err != nil {
			quest_info.Error = err.Error()
		}
		quest_info.QuestLog = quests
		rets = append(rets, quest_info)

		// runtime日志搜素
		runtime_info := LogSearch{
			Type:     "runtime",
			FileName: files[i].Name,
		}
		runtime, runtimes := model.RuntimeLog{}, []model.RuntimeLog{}
		err = db.Table(runtime.TableName()).
			Where("id >= ?", id_min).
			Where("id < ?", id_max).
			Where("did", did).
			Order("id DESC").
			Find(&runtimes).
			Error
		if err != nil {
			runtime_info.Error = err.Error()
		}
		runtime_info.RuntimeLog = runtimes
		rets = append(rets, runtime_info)
	}
	return rets, nil
}
